var md5 = require('md5.min.js');
var config = require('../config.js');
module.exports = {
  loginBand: function (params, callback) {
    var THIS = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var jscode = res.code;
          var ppp = { jscode: jscode }
          if (params.otherId && params.otherId != "undefined") {
            ppp.banrdId = params.banrdId;
            ppp.otherId = params.otherId;
          }
          //发起网络请求
          THIS.request(config.loginAction, ppp, function (protocol) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("pingtai", protocol.data.pingtai);
              wx.setStorageSync("openid", protocol.data.openid);
              wx.setStorageSync("session_key", protocol.data.session_key);
              callback(protocol);
          }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },

  loginNew: function (params, callback) {
    var THIS = this;
    wx.login({
      success: function (res) {
        
        if (res.code) {
          var jscode = res.code;
          params.jscode=jscode;
         
          THIS.request(config.loginAction, params, function (protocol) {
            //if (protocol.data.type == 1) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("pingtai", protocol.data.pingtai);
              wx.setStorageSync("openid", protocol.data.openid);
              wx.setStorageSync("session_key", protocol.data.session_key);
              callback(protocol);
            // } else if (protocol.data.type == 2) {
            //   wx.reLaunch({
            //     url: '/pages/auth?type=1',
            //   })
            // }
          }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  login: function (callback) {
    var THIS = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var jscode = res.code;
          //发起网络请求
          THIS.request(config.loginAction, {
            jscode: jscode
          }, function (protocol) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("pingtai", protocol.data.pingtai);
              wx.setStorageSync("openid", protocol.data.openid);
              wx.setStorageSync("session_key", protocol.data.session_key);
              callback(protocol);
          }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  loginCallback: function (params, callback) {
    var THIS = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var jscode = res.code;
          params.jscode = jscode;
          //发起网络请求
          THIS.request(config.loginAction, params, function (protocol) {
            wx.setStorageSync("token", protocol.data.token);
            wx.setStorageSync("userInfo", protocol.data.userInfo);
            wx.setStorageSync("pingtai", protocol.data.pingtai);
            wx.setStorageSync("openid", protocol.data.openid);
            wx.setStorageSync("session_key", protocol.data.session_key);
            callback(protocol);
          }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  loginGz: function (parmas, callback) {
    var THIS = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var jscode = res.code;
          //发起网络请求
          THIS.request(config.loginAction, {
            gzflag: parmas.gzflag,
            jscode: jscode
          }, function (protocol) {
            if (protocol.data.type == 1) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("pingtai", protocol.data.pingtai);
              wx.setStorageSync("openid", protocol.data.openid);
              wx.setStorageSync("session_key", protocol.data.session_key);
              callback(protocol);
            } else if (protocol.data.type == 2) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("pingtai", protocol.data.pingtai);
              wx.setStorageSync("openid", protocol.data.openid);
              wx.setStorageSync("session_key", protocol.data.session_key);
              callback(protocol);
            }
          }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  loginArt: function (parmas, callback) {
    var THIS = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var jscode = res.code;
          //发起网络请求
          THIS.request(config.loginAction, {
            otherId: parmas.otherId,
            jscode: jscode
          }, function (protocol) {
            if (protocol.data.type == 1) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("pingtai", protocol.data.pingtai);
              wx.setStorageSync("openid", protocol.data.openid);
              wx.setStorageSync("session_key", protocol.data.session_key);
              callback(protocol);
            } else if (protocol.data.type == 2) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("pingtai", protocol.data.pingtai);
              wx.setStorageSync("openid", protocol.data.openid);
              wx.setStorageSync("session_key", protocol.data.session_key);
              callback(protocol);
            }
          }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  redLogin: function (parmas, callback) {
    var THIS = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var jscode = res.code;
          //发起网络请求
          THIS.requestCallBack(config.loginAction, {
            otherId: parseInt(parmas.memberId),
            banrdId: parseInt(parmas.merchant),
            jscode: jscode
          }, function (protocol) {
            if (protocol.data.type == 1) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("pingtai", protocol.data.pingtai);
              wx.setStorageSync("openid", protocol.data.openid);
              wx.setStorageSync("session_key", protocol.data.session_key);
              callback(protocol);
            } else if (protocol.data.type == 2) {
              callback(protocol);
            }
          }, true);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  /**
	 * 请求数据
	 * action:接口标识
	 * data:请求数据
	 * callback:返回值回调(protocol)
	 * toast:protocol中的message是否托管显示
	 */
  requestCallBack: function (action, params, callback, toast) {
    var THIS = this;
    var url = config.apiUrl;
    var data = {};
    if (url.indexOf("/invoke.do") > -1) {
      data.params = params;
      data.method = action;
    } else {
      url += action;
      data = params;
    }
    //自动添加TOKEN参数
    data.token = wx.getStorageSync('token') || "";
    data.timestamp = this.formatTime(new Date());
    data.appid = config.appid;
    data.sign = this.getSign(config.secret, data);
    wx.request({
      url: url,
      data: data,
      header: { 'Content-Type': 'application/json' },
      success: function (res) {
        if (res.statusCode == 200) {
          var protocol = res.data;
          //如果要求显示信息提示
          if (toast && protocol.message) {
            wx.showToast({
              title: protocol.message,
              icon: 'none',
              duration: 2000,
              complete: function () {
                //wx.hideToast();
              }
            })
          }
          callback(protocol);
        } else {//网络请求异常
          THIS.onError(res);
        }
      },
      fail: function (res) {
        THIS.onError(res);
      }
    })
  },
	/**
	 * 请求数据
	 * action:接口标识
	 * data:请求数据
	 * callback:返回值回调(protocol)
	 * toast:protocol中的message是否托管显示
	 */
  request: function (action, params, callback, toast) {
    var THIS = this;
    var url = config.apiUrl;
    var data = {};
      url += action;
      data = params;
    //自动添加TOKEN参数
    data.token = wx.getStorageSync('token') || "";
    data.timestamp = this.formatTime(new Date());
    data.appid = config.appid;
    data.sign = this.getSign(config.secret, data);
   
    wx.request({
      url: url,
      data: data,
      header: { 'Content-Type': 'application/json' },
      success: function (res) {
        
        if (res.statusCode == 200) {
          var protocol = res.data;
          //如果要求显示信息提示
          if (toast && protocol.message) {
            wx.showToast({
              title: protocol.message,
              icon: 'none',
              duration: 2000,
              complete: function () {
                //wx.hideToast();
              }
            })
          }
          //如果返回错误代码为invalid_token，表示需要登录
          if (protocol.error == "invalid_token") {
            wx.reLaunch({ url: config.loginPage });
          } else {//数据请求成功
            callback(protocol);
          }
        } else {//网络请求异常
          THIS.onError(res);
        }
      },
      fail: function (res) {
        console.log(JSON.stringify(res)+"config.res");
        THIS.onError(res);
      }
    })
  },
	/**
	 * 错误处理
	 */
  onError(res) {
    wx.reLaunch({
      url: '/pages/erros/wxerros',
    });
  },
	/**
	 * 获取参数签名
	 */
  getSign: function (secrent, data) {
    var keys = [];
    for (var o in data) keys.push(o);
    keys = keys.sort();
    var strSign = "";
    for (var o in keys) {
      if (keys[o] == "params") {
        strSign += keys[o] + JSON.stringify(data[keys[o]]);
      } else {
        strSign += keys[o] + data[keys[o]];
      }
    }
    strSign = secrent + strSign + secrent;
    return md5(strSign).toUpperCase();
  },
  bin2hex: function (str) {
    var result = "";
    for (i = 0; i < str.length; i++) {
      var c = str.charCodeAt(i);
      result += byte2Hex(c >> 8 & 0xff); // 高字节
      result += byte2Hex(c & 0xff);	// 低字节
    }
    return result;
  },
  byte2Hex: function (b) {
    if (b < 0x10)
      return "0" + b.toString(16);
    else
      return b.toString(16);
  },

	/**
	 * 格式化时间
	 */
  formatTime: function (date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
  },
  formatNumber: function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
	/**
	 * ux测试
	 */
  test: function () {
    console.log("ux加载成功");
  },
  /****************************************解决JS浮点数(小数)计算加减乘除的BUG    Start****************************************/

  /**
  ** 加法函数，用来得到精确的加法结果
  ** 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  ** 调用：accAdd(arg1,arg2)
  ** 返回值：arg1加上arg2的精确结果
  **/
  acAdd: function (arg1, arg2) {
    if (isNaN(arg1)) {
      arg1 = 0;
    }
    if (isNaN(arg2)) {
      arg2 = 0;
    }
    arg1 = Number(arg1);
    arg2 = Number(arg2);
    var r1, r2, m, c;
    try {
      r1 = arg1.toString().split(".")[1].length;
    }
    catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    }
    catch (e) {
      r2 = 0;
    }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2));
    if (c > 0) {
      var cm = Math.pow(10, c);
      if (r1 > r2) {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", "")) * cm;
      } else {
        arg1 = Number(arg1.toString().replace(".", "")) * cm;
        arg2 = Number(arg2.toString().replace(".", ""));
      }
    } else {
      arg1 = Number(arg1.toString().replace(".", ""));
      arg2 = Number(arg2.toString().replace(".", ""));
    }
    return (arg1 + arg2) / m;
  },
  /**
  ** 减法函数，用来得到精确的减法结果
  ** 说明：javascript的减法结果会有误差，在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
  ** 调用：accSub(arg1,arg2)
  ** 返回值：arg1加上arg2的精确结果
  **/
  acSub: function (arg1, arg2) {
    if (isNaN(arg1)) {
      arg1 = 0;
    }
    if (isNaN(arg2)) {
      arg2 = 0;
    }
    arg1 = Number(arg1);
    arg2 = Number(arg2);

    var r1, r2, m, n;
    try {
      r1 = arg1.toString().split(".")[1].length;
    }
    catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg2.toString().split(".")[1].length;
    }
    catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
  },
  /**
  ** 乘法函数，用来得到精确的乘法结果
  ** 说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  ** 调用：accMul(arg1,arg2)
  ** 返回值：arg1乘以 arg2的精确结果
  **/
  acMul: function (arg1, arg2) {
    if (isNaN(arg1)) {
      arg1 = 0;
    }
    if (isNaN(arg2)) {
      arg2 = 0;
    }
    arg1 = Number(arg1);
    arg2 = Number(arg2);

    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
      m += s1.split(".")[1].length;
    }
    catch (e) {
    }
    try {
      m += s2.split(".")[1].length;
    }
    catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  },
  /** 
  ** 除法函数，用来得到精确的除法结果
  ** 说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  ** 调用：accDiv(arg1,arg2)
  ** 返回值：arg1除以arg2的精确结果
  **/
  acDiv: function (arg1, arg2) {
    if (isNaN(arg1)) {
      arg1 = 0;
    }
    if (isNaN(arg2)) {
      arg2 = 0;
    }
    arg1 = Number(arg1);
    arg2 = Number(arg2);

    var t1 = 0, t2 = 0, r1, r2;
    try {
      t1 = arg1.toString().split(".")[1].length;
    }
    catch (e) {
    }
    try {
      t2 = arg2.toString().split(".")[1].length;
    }
    catch (e) {
    }
    r1 = Number(arg1.toString().replace(".", ""));
    r2 = Number(arg2.toString().replace(".", ""));
    return (r1 / r2) * pow(10, t2 - t1);
  }
}